<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--绘制用户列表卡片-->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <!-- 搜索框组件 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="pageParam.param.username"
            clearable
            @clear="getAdminList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getAdminList"
            ></el-button>
          </el-input>
        </el-col>

        <!--添加用户组件-->
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true"
            >添加管理员</el-button
          >
        </el-col>
      </el-row>

      <!-- 卡片内数据表格内容 -->
      <el-table :data="adminList" border style="width: 100%">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="账号"
          width="180"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column label="状态">
          <!-- 设置状态开关模版 -->
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!--设置 修改、删除、设置 按钮-->
          <template v-slot="scope">
           
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateUserDialog(scope.row.adminId)"
            ></el-button>


            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.adminId)"
            ></el-button>

            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="设置"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setUserRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页插件-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.pageNo"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加管理员"
        :visible.sync="addUserDialogVisible"
        width="50%"
        @close="addUserDialogClosed"
      >
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="addUserForm.username"> </el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password">
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"> </el-input>
          </el-form-item>

        </el-form>

        <!-- 添加用户提示框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editUserDialogVisible"
        width="50%"
        @close="editUserDialogClosed"
      >
        <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="70px"
        >
          <el-form-item label="账号" prop="username">
            <el-input disabled v-model="editUserForm.username"> </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"> </el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="editUserForm.password"> </el-input>
          </el-form-item>
        </el-form>

        <!-- 修改用户提示框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配用户角色对话框 -->
      <el-dialog
        title="设置角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="setRoleDialogClosed"
      >
        <div>
          <p>当前用户: {{ userInfo.username }}</p>
          <p>当前角色: {{ userInfo.role_name }}</p>
          <p>
            分配新角色:
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请正确填写邮箱"));
      } else {
        if (value !== "") {
          var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (!reg.test(value)) {
            callback(new Error("请输入有效的邮箱"));
          }
        }
        callback();
      }
    };

    // 验证手机号的规则
    var validateMobilePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("负责人手机号不可为空"));
      } else {
        if (value !== "") {
          var reg = /^1[3456789]\d{9}$/;
          if (!reg.test(value)) {
            callback(new Error("请输入有效的手机号码"));
          }
        }
        callback();
      }
    };

    return {
      // 分页数据
      pageParam: {
        pageSize: 5,
        pageNo: 1,
        param: {
          
        }
      },
      // 总共条数
      total: 0,

      adminList: [],

      // 提示框显示状态
      addUserDialogVisible: false,
      editUserDialogVisible: false,
      setRoleDialogVisible: false,

      userInfo: {},

      //可以分配的角色列表
      rolesList: [],

      // 选中的角色Id 
      selectedRoleId: '',


      // 添加用户表单
      addUserForm: {
        username: "",
        password: "",
        email: "",
        nickName: ""
      },

      // 编辑用户表单
      editUserForm: {},

      // 添加用户自定义规则
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在 3-10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码长度在 6-15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
      },


      //  编辑用户自定义规则
      editUserFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ]
      }

    };
  },

  created() {
    this.getAdminList();
  },


  methods: {
    //获取用户列表数据请求
    async getAdminList() {

      const { data: res } = await this.$http.post("page",this.pageParam);
      if (res.meta.code !== 200) {
        return this.$message.error("获取管理员列表失败!");
      }
      
      this.adminList = res.data.records;
      this.total = res.data.total;
      console.log(res);
    },

    // 当前页显示条数发生改变触发事件
    handleSizeChange(newSize) {
      this.pageParam.pageSize = newSize;
      this.getAdminList();
    },

    // 当前页发生改变触发函数
    handleCurrentChange(newNum) {
      console.log(newNum);
      this.pageParam.pageNo = newNum;
      this.getAdminList();
    },

    // 用户开关改变事件
    async userStateChanged(userInfo) {
      console.log(userInfo);
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );

      if (res.meta.code !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新失败！");
      }
      // 提示用户更新状态成功
      this.$message.success("更新用户状态成功");

      // 本地重新请求服务端，更新用户列表数据
      this.getAdminList();
    },



    // 添加用户对话框关闭事件
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields();
    },

    // 添加用户请求
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        // 检查用户校验是否通过

        if (!valid) {
          return;
        }

        // 发起网络请求、添加用户
        const { data: res } = await this.$http.post("save", this.addUserForm);
        console.log(res);

        if (res.meta.code != 200) {
          return this.$message.error("添加用户失败");
        }

        this.$message.success("添加用户成功");
        // 隐藏添加用户对话框
        this.addUserDialogVisible = false;
        //刷新用户列表
        this.getAdminList();
      });
    },

    // 让修改对话框关闭
    editUserDialogClosed() {
      this.editUserDialogVisible = false;
    },

    //显示更改用户信息 Dialog
    async showUpdateUserDialog(id) {
      this.editUserDialogVisible = true;

      const { data: res } = await this.$http.get("get-by-id/" + id);

      this.editUserForm = res.data;
    },
    

    // 更改用户信息
    editUser() {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) {
          return;
        }

        console.log(this.editUserForm);
        // 发起修改用户信息的请求

        const { data: res } = await this.$http.put("update", this.editUserForm);

        if (res.meta.code !== 200) {
          return this.$message.error("更新用户信息失败!");
        }

        this.editUserDialogVisible = false;

        this.$message.success("更新 用户信息成功!");
        this.getAdminList();
      });
    },


    // 删除用户信息
    removeUserById(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {

          const { data: res } = await this.$http.delete("delete-by-id/" + id);

          if (res.meta.code !== 200) {
            return this.$message.error("删除失败");
          }

          //点击确认删除触发的事件
          this.$message({
            type: "success",
            message: "删除成功!"
          });

          // 重新获取用户列表
          this.getAdminList();
        })
        .catch(() => {
          // 点击取消触发的事件
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },


    // 显示设置用户角色对话框
    async setUserRoleDialog(userInfo) {
      this.userInfo = userInfo;

      const { data: res } = await this.$http.get("roles");

      if (res.meta.code !== 200) {
        return this.$message.error("获取角色列表失败");
      }

      this.rolesList = res.data;

      // 获取好数据再显示对话框
      this.setRoleDialogVisible = true;
    },

    // 保存设置用户角色信息
    async saveRoleInfo(){
      if ( !this.selectedRoleId )
      {
        return this.$message.error('请选择要分配的角色')
      }
      
      const { data:res } = await this.$http.put(`users/${this.userInfo.id}/role`,
      {
        rid: this.selectedRoleId
      })  

      if( res.meta.code !== 200)
      {
        return this.$message.error('设置用户角色失败!')
      }

      this.$message.success('更新角色成功!')

      //更新用户列表
      this.getAdminList()

      // 隐藏设置用户角色对话框
      this.setRoleDialogVisible = false

    },

    setRoleDialogClosed(){
      this.selectedRoleId = '',
      this.userInfo = {}
    }
  }
};
</script>

<style lang="less" scope></style>
